//
//  EFMyDeliveryAddressViewController.m
//  EnjogFood
//
//  Created by guocheng on 2017/5/7.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFMyDeliveryAddressViewController.h"
#import "EFMyDeliveryAddressViewItem.h"
#import "EFNewDeliveryAddressViewController.h"
#import "EFMyDeliveryAddressViewCell.h"
#import "iToast.h"

@interface EFMyDeliveryAddressViewController ()<UITableViewDelegate, UITableViewDataSource>

@property(strong,nonatomic)NSMutableArray* dataArray;
@property(strong,nonatomic)UITableView* tableView;

@property(strong,nonatomic)UIButton* addBtn;

@end

@implementation EFMyDeliveryAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
//    [self initData];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self initData];
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = @"收货地址";
        self.dataArray = [NSMutableArray array];
    }
    return self;
}

-(void)initView{
    [self.view addSubview:self.addBtn];
    [self.view addSubview:self.tableView];
}

-(void)initData{
    [self showHUD];
    [self.dataArray removeAllObjects];
    __weak typeof(self) weakSelf = self;
    [APP_CONTEXT.net addressList:^(NSInteger code, NSDictionary *info, NSString *message) {
        [weakSelf.HUD hide:YES];
        if (code == 0) {
            if ([info objectForKey:@"list"]) {
                NSArray *array = [info objectForKey:@"list"];
                EFMyDeliveryAddressViewItem* defalut = APP_CONTEXT.addressManager.defaultAddress;
                for (NSDictionary *dic in array) {
                    EFMyDeliveryAddressViewItem *item = [EFMyDeliveryAddressViewItem yy_modelWithDictionary:dic];
                    
                    if(defalut != nil && item.id == defalut.id){
                        item.selected = true;
                    }
                    
                    [weakSelf.dataArray addObject:item];
                }
              
                if (array.count == 0) {
                    
                }
            }
            //增加到全局
            APP_CONTEXT.addressManager.addressArray = weakSelf.dataArray;
            [weakSelf.tableView reloadData];
        }else{
            
        } 
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem *item = self.dataArray[indexPath.row];
    return item.viewHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArray count];
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.dataArray removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source.
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem* item = self.dataArray[indexPath.row];
    NSString *identifier = NSStringFromClass(item.viewClass);
    ICTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[item.viewClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if ([item isKindOfClass:[ICTableViewItem class]]) {
        [cell setObject:item];
    }
    
    ((EFMyDeliveryAddressViewCell *)cell).deleteblock = ^{
        [self removeDataWithIndex:indexPath.row];
    };
    
    ((EFMyDeliveryAddressViewCell *)cell).editblock = ^{
        [self editDataWithIndex:indexPath.row];
    };
    
    
    ((EFMyDeliveryAddressViewCell *)cell).selectblock = ^(NSString* id,Boolean bSelect){
        [self modifyData:id select:bSelect];
    };
    
    return cell;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kStatusBarHeight - self.addBtn.height)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.bottom = self.addBtn.top;
    }
    return _tableView;
}

-(UIButton *)addBtn{
    if(_addBtn == NULL){
        _addBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        _addBtn.top = kScreenHeight - kStatusBarHeight -  50;
        _addBtn.backgroundColor = RGBCOLOR(0x69BA45);
        _addBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _addBtn.titleLabel.textColor = [UIColor whiteColor];
        [_addBtn setTitle:@"添加新地址" forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(onClickAdd) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

-(void)onClickAdd{
    EFNewDeliveryAddressViewController *newAddress = [[EFNewDeliveryAddressViewController alloc] initWithLocation];
    [ICNavigator pushViewController:newAddress animated:YES];
}

-(void)removeDataWithIndex:(NSInteger)index{
    EFMyDeliveryAddressViewItem* item = [self.dataArray objectAtIndex:index];
    
    __weak typeof(self) weakSelf = self;
    [APP_CONTEXT.net removeAddressWithId:item.id OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        if(code == 0){
            EFMyDeliveryAddressViewItem* defalut = APP_CONTEXT.addressManager.defaultAddress;
            if(defalut != nil && [defalut.id isEqualToString:item.id]){
                APP_CONTEXT.addressManager.defaultAddress = nil;
                [APP_CONTEXT.addressManager persistenceAddressManager];
            }
            [weakSelf.dataArray removeObjectAtIndex:index];
            [weakSelf.tableView reloadData];
            
        }else{
            [[iToast makeText:message] show];
        }
    } ];
}

-(void)editDataWithIndex:(NSInteger)index{
    EFMyDeliveryAddressViewItem* item = [self.dataArray objectAtIndex:index];
    EFNewDeliveryAddressViewController *address = [[EFNewDeliveryAddressViewController alloc] initWithItem:item];
    [ICNavigator pushViewController:address animated:NO];
}

-(void)modifyData:(NSString*) id select:(Boolean)bSelect{
    __weak typeof(self) weakSelf = self;
    [APP_CONTEXT.net setDefaultAddress:id OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        if(code == 0){
            for (NSObject *object in weakSelf.dataArray) {
                EFMyDeliveryAddressViewItem* item = (EFMyDeliveryAddressViewItem*)object;
                if([id isEqualToString:item.id]){
                    if(bSelect){
                        item.selected = true;
                        APP_CONTEXT.addressManager.defaultAddress = item;
                        [APP_CONTEXT.addressManager persistenceAddressManager];
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:IC_CHANGE_DEFAULT_NOTIFICATION object:nil];
                        [[iToast makeText:@"已设为默认"]show];
                    }else{
                        item.selected = false;
                    }
                    //[weakSelf.navigationController popViewControllerAnimated:YES];
                }else{
                    if(bSelect)
                        item.selected = false;
                }
            }
            [weakSelf.tableView reloadData];
        }
    }];
}




@end
